﻿/*
	Copyright (C) 2019 Zongming Liu <1849059316@qq.com>

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License along
	with this program; if not, write to the Free Software Foundation, Inc.,
	51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "Line.h"
#include "Vector.h"
namespace SkyEngine2d
{
	
	Line::Line()
	{
	
	}
	
	Line::Line(float x_1, float y_1, float x_2, float y_2)
		:startPos(x_1, y_1)
		, endPos(x_2, y_2)
	{
	
	}
	
	Line::Line(const Vector2& pos_1, const Vector2& pos_2)
		:startPos(pos_1)
		, endPos(pos_2)
	{
	
	}
	
	Line::~Line()
	{
	
	}
	
	void Line::move(const Vector2& dt)
	{
		startPos += dt;
		endPos += dt;
	}
	
	bool Line::lineIntersect(const Line& line) const
	{
		//快速排斥实验
		if (max(startPos.x, endPos.x) < min(line.startPos.x, line.endPos.x) ||
			max(startPos.y, endPos.y) < min(line.startPos.y, line.endPos.y) ||
			max(line.startPos.x, line.endPos.x) < min(startPos.x, endPos.x) ||
			max(line.startPos.y, line.endPos.y) < min(startPos.y, endPos.y)
			)
		{
			return false;
		}
	
		//跨立实验
	
		Vector2 u(startPos.x - line.startPos.x, startPos.y - line.startPos.y);
		Vector2 v(startPos.x - line.endPos.x, startPos.y - line.endPos.y);
		Vector2 q(startPos.x - endPos.x, startPos.y - endPos.y);
	
		Vector2 w(endPos.x - line.startPos.x, endPos.y - line.startPos.y);
		Vector2 z(endPos.x - line.endPos.x, endPos.y - line.endPos.y);
		Vector2 p(endPos.x - startPos.x, endPos.y - startPos.y);
	
		if (Vector2::dot(Vector2::cross(u, q), Vector2::cross(v, q)) > 0
			|| Vector2::dot(Vector2::cross(w, p), Vector2::cross(z, p)) > 0)
		{
			return false;
		}
	
		return true;
	}
}